package com.ruoyi.framework.web.service;

import javax.annotation.Resource;

import com.ruoyi.common.core.domain.entity.Person;
import com.ruoyi.common.core.domain.entity.UkLoginInfo;
import com.ruoyi.common.exception.user.*;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.jm.GmUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.IPersonService;
import com.ruoyi.system.service.IUkLoginInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 登录校验方法
 *
 * @author ess
 */
@Component
public class SysLoginService {
    private static final Logger log = LoggerFactory.getLogger(SysLoginService.class);


    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IPersonService personService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private IUkLoginInfoService ukLoginInfoService;

    @Value(value = "${ess.maxRetryCount}")
    private String maxRetryCount;

    /**
     * 登录验证
     *
     * @param username 用户名   重名时格式为 姓名-生日
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid, String ukeyToken, String birNum) {
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关
        if (captchaOnOff) {
            validateCaptcha(username, code, uuid);
        }

//        判断redis中密码错误次数
        Integer countRetry = (Integer) redisCache.getCacheObject("maxRetryCount" + username + birNum);

        if (countRetry != null && countRetry >= Integer.valueOf(maxRetryCount).intValue()) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount)));
//        设置过期时间
            if (countRetry == 100) {
//                防止重复计时
            } else {
                redisCache.setCacheObject("maxRetryCount" + username + birNum, 100);
                redisCache.expire("maxRetryCount" + username + birNum, 300);
            }

            redisCache.deleteObject(username);
            throw new UserPasswordRetryLimitExceedException(Integer.valueOf(maxRetryCount).intValue());
        }


        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
//              redis中错误次数加1
                if (countRetry == null) {
                    redisCache.setCacheObject("maxRetryCount" + username + birNum, 1);
                } else {
                    redisCache.setCacheObject("maxRetryCount" + username + birNum, countRetry + 1);
                }
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }

        //              redis中错误次数删除
        redisCache.deleteObject("maxRetryCount" + username + birNum);

        String depId = (String) redisCache.getCacheObject(username);
        SysUser user = userService.selectUserByUserNameAndDepId(username, depId);
        redisCache.deleteObject(username);

//        20220510 增加管理员ukey登录
        UkLoginInfo ukLoginInfo = ukLoginInfoService.selectUkLoginInfoByPersonId(user.getPersonId());
        if (ukLoginInfo != null && StringUtils.isEmpty(ukeyToken)) {
            String Uuid = IdUtils.fastSimpleUUID();
            redisCache.setCacheObject("ukeyUuid" + username + birNum, Uuid);
            return Constants.UK_LOGIN + "@" + ukLoginInfo.getUkCert() + "@" + Uuid;
        } else if (ukLoginInfo != null && StringUtils.isNotEmpty(ukeyToken)) {
            String ukeyUuid = (String) redisCache.getCacheObject("ukeyUuid" + username + birNum);
            redisCache.deleteObject("ukeyUuid" + username + birNum);

//            验证token
            String hashStrN =Constants.UK_HASH_PSW+ukeyUuid+ukLoginInfo.getUkCert();
            String sm3Hash = Base64Utils.ESSGetBase64Encode(GmUtil.sm3(hashStrN.getBytes()));
            if (!ukeyToken.equals(sm3Hash)) {
                throw new UserException("TOKEN认证失败",null);
            }

        }


        Person person = personService.selectPersonByPersonId(user.getPersonId());
        //        默认密码强制修改
        if (person.getLoginPsw().equals(Constants.DEFAULT_PASS)) {
            log.info("登录用户：{} 需修改默认密码.", username);
            return Constants.UPDATE_PASSWD + "@" + user.getUserId();
        }
//        密码修改周期90天判断 和默认密码强制修改
        String passwordValidateDays = sysConfigService.selectConfigByKey("sys.account.passwordValidateDays");
        Boolean resBool = SecurityUtils.passwordIsExpiration(Integer.valueOf(passwordValidateDays), person.getPwdUpdateDate());
        if (resBool) {
            log.info("登录用户：{} 密码过期,修改密码.", username);
            return Constants.UPDATE_PASSWD + "@" + user.getUserId();
        }


        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    /**
     * 默认密码修改   密码过期
     *
     * @param username
     * @return
     */
    public String checkPasswd(String username) {

        String depId = (String) redisCache.getCacheObject(username);
        SysUser user = userService.selectUserByUserNameAndDepId(username, depId);
        redisCache.deleteObject(username);
        Person person = personService.selectPersonByPersonId(user.getPersonId());
        //        默认密码强制修改
        if (person.getLoginPsw().equals(Constants.DEFAULT_PASS)) {
            log.info("登录用户：{} 需修改默认密码.", username);
            return Constants.UPDATE_PASSWD;
        }
//        密码修改周期90天判断 和默认密码强制修改
        String passwordValidateDays = sysConfigService.selectConfigByKey("sys.account.passwordValidateDays");
        Boolean resBool = SecurityUtils.passwordIsExpiration(Integer.valueOf(passwordValidateDays), person.getPwdUpdateDate());
        if (resBool) {
            log.info("登录用户：{} 密码过期,修改密码.", username);
            return Constants.UPDATE_PASSWD;
        }


        return "";
    }
}
